#!/usr/bin/env python3
"""
删除脚本：删除所有标签为 yanxx 的节点
"""

import asyncio
import json
import sys

try:
    from mcp import ClientSession, StdioServerParameters  # type: ignore
    from mcp.client.stdio import stdio_client  # type: ignore
except ImportError:
    print("Error: mcp not found. Please install the MCP SDK.")
    sys.exit(1)

async def delete_yanxx_nodes():
    """删除所有 yanxx 标签节点的函数"""
    server_params = StdioServerParameters(
        command="uv",
        args=["run", "python", "main.py"],
        env=None
    )
    
    async with stdio_client(server_params) as (read, write):
        async with ClientSession(read, write) as session:
            # 初始化会话
            await session.initialize()
            
            print("正在查询所有 yanxx 标签的节点...")
            
            # 首先查询所有 yanxx 节点
            query_result = await session.call_tool(
                "query_nodes",
                {
                    "label": "yanxx",
                    "limit": 100  # 设置较大的限制以获取所有节点
                }
            )
            
            nodes_to_delete = []
            for content in query_result.content:
                if hasattr(content, 'text'):
                    try:
                        data = json.loads(content.text)
                        if isinstance(data, list):
                            nodes_to_delete = data
                            print(f"找到 {len(nodes_to_delete)} 个 yanxx 节点")
                        else:
                            print(f"查询结果: {data}")
                            return
                    except json.JSONDecodeError:
                        print(f"查询失败: {content.text}")
                        return
            
            if not nodes_to_delete:
                print("没有找到任何 yanxx 标签的节点")
                return
            
            # 删除每个节点
            deleted_count = 0
            for i, node in enumerate(nodes_to_delete, 1):
                node_id = None
                if isinstance(node, dict):
                    node_id = node.get('id') or node.get('element_id')
                    properties = node.get('properties', {})
                    print(f"\n正在删除节点 {i}/{len(nodes_to_delete)}: ID={node_id}, 属性={properties}")
                else:
                    print(f"\n节点格式异常: {node}")
                    continue
                
                if node_id:
                    try:
                        delete_result = await session.call_tool(
                            "delete_node",
                            {"node_id": str(node_id)}
                        )
                        
                        for content in delete_result.content:
                            if hasattr(content, 'text'):
                                print(f"  删除结果: {content.text}")
                                if "successfully" in content.text.lower() or "deleted" in content.text.lower():
                                    deleted_count += 1
                            else:
                                print(f"  删除结果: {content}")
                    except Exception as e:
                        print(f"  删除节点 {node_id} 时出错: {e}")
                else:
                    print(f"  无法获取节点 ID")
            
            print(f"\n=== 删除完成 ===")
            print(f"成功删除 {deleted_count} 个节点")
            
            # 验证删除结果
            print("\n正在验证删除结果...")
            verify_result = await session.call_tool(
                "query_nodes",
                {
                    "label": "yanxx",
                    "limit": 10
                }
            )
            
            for content in verify_result.content:
                if hasattr(content, 'text'):
                    try:
                        data = json.loads(content.text)
                        if isinstance(data, list):
                            print(f"验证结果: 还剩余 {len(data)} 个 yanxx 节点")
                        else:
                            print(f"验证结果: {data}")
                    except json.JSONDecodeError:
                        print(f"验证结果: {content.text}")

if __name__ == "__main__":
    asyncio.run(delete_yanxx_nodes())